<template>
  <view class="package-container">
    <!-- 顶部返回与标题 -->
    <view class="header">
      <button class="back-btn" @click="goBack">
        <image src="/static/icons/back.png" class="back-icon" mode="widthFix" />
      </button>
    </view>

    <!-- 顶部功能标签 -->
    <view class="top-tags">
      <view class="tag-item">通话</view>
      <view class="tag-item">作业批改</view>
      <view class="tag-item">智能出题</view>
      <view class="tag-item">权益</view>
    </view>

    <!-- 套餐列表 -->
    <view class="package-list">
      <view
          class="package-item"
          v-for="(pkg, idx) in packages"
          :key="pkg.id"
          :class="{ 'selected': selectedPackageId === String(pkg.id) }"
          @click="selectPackage(pkg)"
      >
        <!-- 悬浮的绿色标签 -->
        <view class="package-badge">
          {{ pkg.packageName }}
        </view>

        <!-- 选中状态指示器 -->
        <view class="selection-indicator" v-if="selectedPackageId === String(pkg.id)">
          <image src="/static/icons/checked.png" class="check-icon" mode="widthFix" />
        </view>

        <view class="package-info">
          <view class="package-desc">{{ pkg.serviceDesc }}</view>
          <view class="package-price">
            ¥{{ pkg.price }}
            <text class="price-icon" v-if="pkg.discountPriceFen">↓</text>
            <text class="original-price" v-if="pkg.discountPriceFen">
              原价¥{{ pkg.priceFen / 100 }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 立即购买按钮（选中后显示） -->
    <view
        class="buy-btn"
        @click="handleBuyClick"
        v-if="selectedPackageId"
        :class="{ 'is-disabled': isSubmitting }"
        :disabled="isSubmitting"
    >
      {{ isSubmitting ? '处理中...' : '立即购买' }}
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import request from '@/utils/request.js'; // 引入封装的请求工具

// --- 1. 防抖动函数 ---
// 在指定时间内，多次调用只执行最后一次
const debounce = (fn, delay = 500) => {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// --- 2. 状态管理 ---
// 套餐数据（从后端获取）
const packages = ref([]);
// 选中的套餐ID（使用字符串类型确保匹配）
const selectedPackageId = ref(null);
// 增加一个状态锁，用于防止重复提交
const isSubmitting = ref(false);

/**
 * 从后端接口获取套餐列表
 */
const fetchPackages = async () => {
  try {
    const res = await request.get('agent/package/activePackages');
    // 业务状态码判断：仅code=200时处理成功逻辑
    if (res.code === 200) {
      const formattedPackages = res.data.map(pkg => ({
        ...pkg,
        price: (pkg.discountPriceFen || pkg.priceFen) / 100
      }));
      packages.value = formattedPackages;
      // 自动选中第一个套餐（若有）
      if (formattedPackages.length > 0) {
        selectedPackageId.value = String(formattedPackages[0].id);
      }
    } else {
      // 业务错误：显示后端返回的错误信息
      uni.showToast({ title: res.msg || '获取套餐列表失败', icon: 'none' });
    }
  } catch (error) {
    // 网络/系统错误：如401、断网等
    console.error('获取套餐失败：', error);
    uni.showToast({ title: '网络异常，请稍后再试', icon: 'none' });
  }
};

onMounted(() => {
  fetchPackages();
});

/**
 * 选择套餐
 */
const selectPackage = (pkg) => {
  selectedPackageId.value = String(pkg.id);
};

/**
 * 核心业务逻辑：创建订单并跳转支付页
 * 这个函数只处理业务，不直接绑定到@click
 */
const createOrderAndPay = async () => {
  if (!selectedPackageId.value) {
    return uni.showToast({ title: '请先选择套餐', icon: 'none' });
  }

  const selectedPkg = packages.value.find(p => String(p.id) === selectedPackageId.value);
  if (!selectedPkg) return;

  try {
    // 发起请求前，将状态锁设为true
    isSubmitting.value = true;

    const res = await request.post('agent/order/create', {
      packageId: selectedPkg.id
    });

    // 业务状态码判断：仅code=200时跳转支付页
    if (res.code === 200) {
      const orderPo = res.data;
      uni.navigateTo({
        url: `/pages/package/pay?orderNo=${orderPo.orderNo}&price=${selectedPkg.price}`
      });
    } else {
      // 业务错误：显示后端返回的错误信息
      uni.showToast({ title: res.msg || '创建订单失败', icon: 'none' });
    }

  } catch (error) {
    // 网络/系统错误：如401、断网等
    console.error('创建订单失败：', error);
    uni.showToast({ title: '网络异常，请稍后再试', icon: 'none' });
  } finally {
    // 无论成功或失败，最终都释放状态锁
    isSubmitting.value = false;
  }
};

/**
 * 点击“立即购买”的处理函数
 * 使用防抖动函数包装核心业务逻辑，形成双重保障
 */
const handleBuyClick = debounce(createOrderAndPay, 800);

/**
 * 返回上一页
 */
const goBack = () => {
  uni.navigateBack();
};
</script>

<style scoped>
* {
  box-sizing: border-box;
}

.package-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f0f9f5;
  padding: 0 15px;
  padding-top: 20px;
}

.header {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  padding: 5px;
  background: transparent;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 24px;
  height: 24px;
}

.top-tags {
  width: 100%;
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  padding: 6px 14px;
  background-color: #fff;
  border-radius: 20px;
  font-size: 14px;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.package-list {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
}

.package-item {
  width: 100%;
  background: #fff;
  border-radius: 12px;
  padding: 20px 15px 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.02);
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  transition: all 0.3s ease;
  border: 2px solid #d9f7e9;
  cursor: pointer;
}

.package-item.selected {
  border-color: #409627;
  box-shadow: 0 4px 12px rgba(64, 150, 39, 0.2);
  background-color: #f9fff7;
  transform: translateY(-2px);
}

.package-badge {
  width: auto;
  min-width: 33%;
  text-align: center;
  background-color: #67c23a;
  color: #fff;
  padding: 6px 15px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  position: absolute;
  top: -10px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
}

.selection-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  background-color: #409627;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon {
  width: 16px;
  height: 16px;
}

.package-info {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: center;
  margin-top: 15px;
}

.package-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  text-align: center;
  padding: 0 5px;
}

.package-price {
  font-size: 18px;
  color: #ff4d4f;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.original-price {
  font-size: 13px;
  color: #999;
  text-decoration: line-through;
}

.price-icon {
  font-size: 14px;
  color: #ff4d4f;
}

/* --- 3. 购买按钮样式 --- */
.buy-btn {
  width: 90%;
  height: 48px;
  line-height: 48px;
  text-align: center;
  background-color: #67c23a;
  color: #fff;
  font-size: 18px;
  font-weight: 500;
  border-radius: 25px;
  margin: 15px 0 30px;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  transition: background-color 0.2s;
}

.buy-btn:active {
  background-color: #52a42c;
}

/* --- 4. 按钮禁用状态样式 --- */
.buy-btn.is-disabled {
  background-color: #b3d8ff;
  box-shadow: none;
  color: #fff;
  cursor: not-allowed;
}
</style>